//
//  Created by Rene Dohan on 11/14/11.
//


#import "PapRequest.h"
#import "NSString+SBJSON.h"
#import "PapRequestListener.h"
#import "UrlBuilder.h"
#import "Application.h"


@implementation PapRequest {
    BOOL success;
}

@synthesize listener, action, data;

- (id)init {
    builder = [UrlBuilder new];
    success = false;
    return self;
}

- (BOOL)success {
    return success;
}

- (NSString *)createTimestamp {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    return [formatter stringFromDate:date];
}

- (NSString *)getUrl {
    builder.baseUrl = [[Application getInstance] url];
    builder.action = action;
    [builder addArgument:@"session" with:[[Application getInstance] session]];
    [builder addArgument:@"ts" with:[self createTimestamp]];
    return [builder getUrl];
}


- (void)onResultsReady:(NSDictionary *)results {
    data = results;
    success = [[data objectForKey:@"success"] boolValue];
    [[self listener] onRequestLoaded:self];
}

- (void)send {
    NSURL *fullUrl = [NSURL URLWithString:[self getUrl]];
    NSLog(@"sending request %@", fullUrl);
    NSURLRequest *request = [NSURLRequest requestWithURL:fullUrl
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60.0];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        receivedData = [NSMutableData new];
    } else {
        NSLog(@"connection failed");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)newData {
    [receivedData appendData:newData];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed! Error - %@ %@",
            [error localizedDescription],
            [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    [[self listener] onRequestFailed:self];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);
    NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSLog(@"%@", dataString.description);
    @try {
        NSDictionary *results = [dataString JSONValue];
        [self onResultsReady:results];
    } @catch (NSException *ex) {
        NSLog(@"%@", ex.description);
        [[self listener] onRequestFailed:self];
    }
}

- (void)addArgument:(NSString *)argument :(NSString *)value {
    [builder addArgument:argument with:value];
}
@end